import AsyncStorage from '@react-native-async-storage/async-storage';
import { router } from 'expo-router';
import { Alert, Platform } from 'react-native';
type HttpClientConfig = {
  baseUrl?: string;
  headers?: Record<string, string>;
};

type RequestOptions<T = any> = {
  params?: Record<string, any>;
  data?: T;
  contentType?: ContentTypeEnum;
  files?: FileParam[];
};

type FileParam = {
  name: string;
  uri: string;
  type?: string;
};


// 通用请求头
export enum ContentTypeEnum {
  Json = 'application/json;charset=UTF-8',
  FormURLEncoded = 'application/x-www-form-urlencoded;charset=UTF-8',
  FormData = 'multipart/form-data;charset=UTF-8',
}

export function createHttpClient(config: HttpClientConfig = {}) {
  let token: string | null = null;
  const pendingRequests = new Map<string, AbortController>();

  const baseUrl = config.baseUrl || '';
  const defaultHeaders = {
    'Accept': ContentTypeEnum.Json,
    ...(config.headers || {})
  };

  const handleError = (error: Error) => {
    //console.error('Request failed:', error);
    //Alert.alert('请求错误', error.message || '未知错误');
  };

  const processResponse = async (response: Response) => {
    if (!response.ok) {
      const errorData = await response.json().catch(() => null);
      if(response.status == 401){ // 未登錄，請重新登陸
        console.warn('请实现路由跳转逻辑，当前 router 未定义');
        if(Platform.OS == 'web'){
          return router.push("/");
        }
        Alert.alert('Tip', '401 Unauthorized',[{text:'OK',onPress:()=>{
          router.push("/");
          // 由于找不到 router，这里暂时无法直接使用，可考虑传入路由函数或使用全局路由方案
          // 以下仅为示例，实际使用时需要根据项目选用的路由库实现
          // 此处假设使用 react-native 提供的导航方式，需要根据实际情况修改
          // 你可以在调用处传入导航函数，或者使用全局导航实例
        }}]);
        return false;
      }else{
        throw new Error(errorData?.message || `HTTP error! status: ${response.status}`);
      }
    }
    return response.json();
  };

  const request = async <T = any>(
    method: string,
    endpoint: string,
    options: RequestOptions = {}
  ): Promise<T> => {
    const controller = new AbortController();
    const requestKey = `${method}_${endpoint}_${Date.now()}`;
    pendingRequests.set(requestKey, controller);

    try {
      const headers = new Headers(defaultHeaders);
      let body: BodyInit | null = null;
      let url = `${baseUrl}${endpoint}`;
      console.log(url)
      // 处理URL参数
      if (options.params) {
        const query = new URLSearchParams(options.params).toString();
        url += `${url.includes('?') ? '&' : '?'}${query}`;
      }

      // 添加认证token
      const user = await AsyncStorage.getItem('USER-INFO');
      if(user != null && user != ''){
         const userinfo = JSON.parse(user);
         
         token = userinfo?.token;
      }
      if (token) {
        //headers.append('Authorization', `Bearer ${token}`);
        headers.append('token', `${token}`);
      }

      // 处理不同内容类型
      if (['POST', 'PUT', 'PATCH'].includes(method.toUpperCase())) {
        switch (options.contentType) {
          case ContentTypeEnum.FormData: {
            const formData = new FormData();
            
            // 添加普通字段
            if (options.data) {
              Object.entries(options.data).forEach(([key, value]) => {
                formData.append(key, value);
              });
            }

            // 添加文件
            options.files?.forEach(({ name, uri, type }) => {
              formData.append(name, {
                uri,
                type: type || 'image/jpeg',
                name: `${Date.now()}.${type?.split('/')[1] || 'jpg'}`
              } as any);
            });

            body = formData;
            break;
          }

          case ContentTypeEnum.FormURLEncoded:
            headers.set('Content-Type', ContentTypeEnum.FormURLEncoded);
            body = new URLSearchParams(options.data).toString();
            break;

          case ContentTypeEnum.Json:
          default:
            headers.set('Content-Type', ContentTypeEnum.Json);
            body = JSON.stringify(options.data);
            break;
        }
      }

      const response = await fetch(url, {
        method,
        headers,
        body,
        signal: controller.signal
      });
      // 處理返回的結果
      const res = await processResponse(response);
      if(res && res.code === 0 && res.msg && res.msg !== '' ){
          handleError(res.msg);
          return res;
      }
      return res;
    } catch (error) {
      if (error instanceof Error && error.name !== 'AbortError') {
        handleError(error);
      }
      throw error;
    } finally {
      pendingRequests.delete(requestKey);
    }
  };

  return {
    setToken: (newToken: string | null) => {
      token = newToken;
    },
    get: <T = any>(endpoint: string, options?: Omit<RequestOptions, 'data'>) => {
      return request<T>('GET', endpoint, options);
    },

    post: <T = any>(endpoint: string, options?: RequestOptions) => {
      return request<T>('POST', endpoint, options);
    },

    upload: <T = any>(endpoint: string, files: FileParam[], data?: Record<string, any>) => {
      return request<T>('POST', endpoint, {
        contentType: ContentTypeEnum.FormData,
        files,
        data
      });
    },

    cancelAll: () => {
      pendingRequests.forEach(controller => controller.abort());
      pendingRequests.clear();
    }
  };
}

// 使用示例
/*
const api = createHttpClient({
  baseUrl: 'https://api.example.com',
  headers: {
    'X-Client-Type': 'mobile'
  }
});

// GET请求
api.get<{ users: User[] }>('/users', {
  params: { page: 1 }
});

// POST JSON
api.post<LoginResponse>('/login', {
  data: { username: 'admin', password: '123456' }
});

// 上传文件
api.upload<UploadResult>('/upload', [
  { name: 'avatar', uri: 'file://path/to/image.jpg' }
], { description: '用户头像' });
*/